import React from "react";
import {Text, View} from "react-native";
import FormStyle from "../style/form-style";
import RadioBox from "../../common/radio-box";

export default class FormCheckBoxGroupWidget extends React.Component {

    _onSelectedChange(item) {
        let selectedItems = this.props.selectedItems ? this.props.selectedItems : [];
        let index = selectedItems.indexOf(item);
        if (index === -1) {
            selectedItems.push(item)
        } else {
            selectedItems.splice(index, 1)
        }

        if (this.props.onSelectedChange) {
            this.props.onSelectedChange(selectedItems);
        }
    }

    _getCheckBox(item) {
        return (
            <RadioBox key={item.id}
                      name={item.name}
                      checkedStyle={_style.checkedCheckBox}
                      normalStyle={_style.normalCheckBox}
                      checked={this._isCheck(item)}
                      onClick={() => this._onSelectedChange(item)}/>
        )
    }

    _isCheck(item) {
        if (this.props.selectedItems) {
            for (let i = 0; i < this.props.selectedItems.length; i++) {
                if (this.props.selectedItems[i].id === item.id) {
                    return true;
                }
            }
        }
        return false;
    }

    render() {
        return (
            <View style={[FormStyle.row, {flexDirection: 'column', alignItems: 'stretch'}, this.props.style]}>
                <Text style={FormStyle.rowLeft}>
                    {this.props.name}
                </Text>
                <View style={[FormStyle.rowRight, {flexDirection: 'column', flexWrap: 'wrap', marginTop: 6}]}>
                    {
                        this.props.options.map((item, index) => {
                            return this._getCheckBox(item)
                        })
                    }
                </View>
            </View>
        )
    }
}

const _style = {
    normalCheckBox: {
        borderRadius:2,
    },
    checkedCheckBox: {
        borderRadius:2,
    }
};
